package com.wceManage.services.impl;

import com.wceManage.beans.SysMenu;
import com.wceManage.data.mapper.BaseMapper;
import com.wceManage.data.mapper.SysMenuMapper;
import com.wceManage.services.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysMenuServiceImpl extends BaseServiceImpl<SysMenu> implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public BaseMapper<SysMenu> getMapper() {
        return sysMenuMapper;
    }

    @Override
    public List<SysMenu> findByUserId(SysMenu sysMenu) {
        return sysMenuMapper.findByUserId(sysMenu);
    }

    @Override
    public List<SysMenu> findByUserIdByShow(SysMenu sysMenu) {
        return sysMenuMapper.findByUserIdByShow(sysMenu);
    }

    @Override
    public void saveReSource(SysMenu sysMenu) {
        // 获取父节点实体
        sysMenu.setParent(this.queryById(sysMenu.getParent().getMenuId()));

        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = sysMenu.getPerms();

        // 设置新的父节点串
        sysMenu.setPerms(sysMenu.getParent().getPerms() + sysMenu.getParent().getMenuId() + ",");

        // 保存或更新实体
        if (sysMenu.getMenuId() == null) {
            sysMenuMapper.add(sysMenu);
        } else {
            sysMenuMapper.update(sysMenu);
        }

        // 更新子节点 parentIds
        SysMenu m = new SysMenu();
        m.setPerms("%," + sysMenu.getMenuId() + ",%");
        List<SysMenu> list = sysMenuMapper.findByParentIdsLike(m);
        for (SysMenu e : list) {
            e.setPerms(e.getPerms().replace(oldParentIds, sysMenu.getPerms()));
            sysMenuMapper.updateParentIds(e);
        }
    }

    @Override
    public int updateSort(SysMenu sysMenu) {
        return sysMenuMapper.updateSort(sysMenu);
    }
}
